<template>
  <div class="statistics-container">
    <el-breadcrumb class="breadcrumb-margin" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>数据统计</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="main-card">
      <div class="toolbar">
        <el-select v-model="selectedRange" placeholder="请选择时间范围" @change="handleRangeChange">
          <el-option label="近7天" value="last7Days"></el-option>
          <el-option label="近一个月" value="last30Days"></el-option>
          <el-option label="本周" value="thisWeek"></el-option>
          <el-option label="本月" value="thisMonth"></el-option>
          <el-option label="昨日" value="yesterday"></el-option>
        </el-select>
      </div>

      <!-- 营业额图表容器 -->
     <el-row :gutter="20">
        <el-col :span="24">
          <div class="chart-container">
            <h3><i class="el-icon-money"></i> 营业额统计</h3>
            <div id="turnoverChart" class="chart"></div>
          </div>
        </el-col>
      </el-row>
      <el-divider></el-divider>
       <el-row :gutter="20">
        <el-col :span="12">
          <div class="chart-container">
            <h3><i class="el-icon-user"></i> 用户统计</h3>
            <div id="userChart" class="chart"></div>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="chart-container">
            <h3><i class="el-icon-s-order"></i> 订单统计</h3>
            <div class="order-statistics">
              <el-row>
                <el-col :span="8">
                  <div class="stat-item">
                    <div class="stat-label">总订单数</div>
                    <div class="stat-value">{{ totalOrderCount }}</div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="stat-item">
                    <div class="stat-label">有效订单数</div>
                    <div class="stat-value">{{ validOrderCount }}</div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="stat-item">
                    <div class="stat-label">订单完成率</div>
                    <div class="stat-value">{{ orderCompletionRate }}%</div>
                  </div>
                </el-col>
              </el-row>
            </div>
            <div id="orderChart" class="chart"></div>
          </div>
        </el-col>
      </el-row>

      <el-divider></el-divider>

      <el-row :gutter="20">
        <el-col :span="24">
          <div class="chart-container">
            <h3><i class="el-icon-dish"></i> Top 10 销量菜品</h3>
            <div id="top10Chart" class="chart"></div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script>
import * as echarts from "echarts";
import dayjs from 'dayjs';

export default {
  name: "ReportVue",
  data() {
    return {
      turnover: {
        dateList: [],
        turnoverList: [],
      },
      users: {
        dateList: [],
        totalUserList: [],
        newUserList: [],
      },
      orders: {
        dateList: [],
        orderCountList: [],
        validOrderCountList: [],
      },
       totalOrderCount: 0,  // 新增属性
      validOrderCount: 0,   // 新增属性
      orderCompletionRate: 0 ,// 新增属性
      top10: {
        nameList: [],
        numberList: [],
      },
      selectedRange: 'last7Days',
    };
  },
  methods: {
    initTurnoverChart() {
      const chartDom = document.getElementById('turnoverChart');
      const myChart = echarts.init(chartDom);
      const option = {
        title: { text: '营业额折线图' },
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: this.turnover.dateList
        },
        yAxis: {
          type: 'value',
          axisLabel: { formatter: '{value} 元' }
        },
        series: [{
          name: '营业额',
          type: 'line',
          data: this.turnover.turnoverList,
          smooth: true,
          label: {
            show: true,
            position: 'top',
            formatter: '{c} 元'
          }
        }]
      };

      myChart.setOption(option);
    },

    initUserChart() {
      const chartDom = document.getElementById('userChart');
      const myChart = echarts.init(chartDom);
      const option = {
        title: { text: '用户统计折线图' },
        tooltip: { trigger: 'axis' },
        legend: {
          data: ['总用户', '新用户']
        },
        xAxis: {
          type: 'category',
          data: this.users.dateList
        },
        yAxis: {
          type: 'value',
          axisLabel: { formatter: '{value}' }
        },
        series: [
          {
            name: '总用户',
            type: 'line',
            data: this.users.totalUserList,
            smooth: true,
            label: {
              show: true,
              position: 'top',
              formatter: '{c}'
            }
          },
          {
            name: '新用户',
            type: 'line',
            data: this.users.newUserList,
            smooth: true,
            label: {
              show: true,
              position: 'top',
              formatter: '{c}'
            }
          }
        ]
      };
      myChart.setOption(option);
    },
    initOrderChart() {
      const chartDom = document.getElementById('orderChart');
      const myChart = echarts.init(chartDom);
      const option = {
        title: { text: '订单统计折线图' },
        tooltip: { trigger: 'axis' },
        legend: {
          data: ['订单总数', '有效订单数']
        },
        xAxis: {
          type: 'category',
          data: this.orders.dateList
        },
        yAxis: {
          type: 'value',
          axisLabel: { formatter: '{value}' }
        },
        series: [
          {
            name: '订单总数',
            type: 'line',
            data: this.orders.orderCountList,
            smooth: true,
            label: {
              show: true,
              position: 'top',
              formatter: '{c}'
            }
          },
          {
            name: '有效订单数',
            type: 'line',
            data: this.orders.validOrderCountList,
            smooth: true,
            label: {
              show: true,
              position: 'top',
              formatter: '{c}'
            }
          }
        ]
      };
      myChart.setOption(option)
    },
        initTop10Chart() {
      const chartDom = document.getElementById('top10Chart');
      const myChart = echarts.init(chartDom);
      const option = {
        title: { text: 'Top 10 销量菜品' },
        tooltip: { trigger: 'axis' },
        xAxis: {
          type: 'category',
          data: this.top10.nameList,
        },
        yAxis: {
          type: 'value',
          axisLabel: { formatter: '{value}' },
        },
        series: [{
          name: '销量',
          type: 'bar',
          data: this.top10.numberList,
          label: {
            show: true,
            position: 'top',
            formatter: '{c}',
          },
        }],
      };
      myChart.setOption(option);
    },

    fetchData(startDate, endDate) {
      // 获取营业额数据
      this.$http.get("/webPage/report/turnoverStatistic", {
        params: { startDate, endDate }
      }).then(response => {
        if (response.data.code === 1) {
          const data = response.data.data;
          this.turnover.dateList = data.dateList.split(',');
          this.turnover.turnoverList = data.turnoverList.split(',').map(Number);
          this.initTurnoverChart();
        } else {
          console.error("营业额数据获取失败：", response.data.message);
        }
      }).catch(error => {
        console.error("营业额请求失败：", error);
      });

      // 获取用户统计数据
      this.$http.get("/webPage/report/userStatistic", {
        params: { startDate, endDate }
      }).then(response => {
        if (response.data.code === 1) {
          const data = response.data.data;
          this.users.dateList = data.dateList.split(',');
          this.users.totalUserList = data.totalUserList.split(',').map(Number);
          this.users.newUserList = data.newUserList.split(',').map(Number);
          this.initUserChart();
        } else {
          console.error("用户数据获取失败：", response.data.message);
        }
      }).catch(error => {
        console.error("用户请求失败：", error);
      });

      this.$http.get("/webPage/report/orderStatistic", {
        params: { startDate, endDate }
      }).then(response => {
        if (response.data.code === 1) {
          const data = response.data.data;
          this.orders.dateList = data.dateList.split(',');
          this.orders.orderCountList = data.orderCountList.split(',').map(Number);
          this.orders.validOrderCountList = data.validOrderCountList.split(',').map(Number);
             // 设置总订单数、有效订单数和订单完成率
          this.totalOrderCount = data.totalOrderCount;
          this.validOrderCount = data.validOrderCount;
          this.orderCompletionRate = (data.orderCompletionRate * 100) .toFixed(2); // 保留两位小数
          this.initOrderChart();
        } else {
          console.error("订单数据获取失败：", response.data.message);
        }
      }).catch(error => {
        console.error("订单请求失败：", error);
      });

       this.$http.get("/webPage/report/top10", {
        params: { startDate, endDate }
      }).then(response => {
        if (response.data.code === 1) {
          const data = response.data.data;
          this.top10.nameList = data.nameList.split(',');
          this.top10.numberList = data.numberList.split(',').map(Number);
          this.initTop10Chart();
        } else {
          console.error("Top 10 菜品数据获取失败：", response.data.message);
        }
      }).catch(error => {
        console.error("Top 10 菜品请求失败：", error);
      });
    },
    
    handleRangeChange() {
      const today = dayjs();
      let startDate = '';
      let endDate = today.format('YYYY-MM-DD');

      switch (this.selectedRange) {
        case 'last7Days':
          startDate = today.subtract(7, 'day').format('YYYY-MM-DD');
          break;
        case 'last30Days':
          startDate = today.subtract(30, 'day').format('YYYY-MM-DD');
          break;
        case 'thisWeek':
          startDate = today.startOf('week').format('YYYY-MM-DD');
          break;
        case 'thisMonth':
          startDate = today.startOf('month').format('YYYY-MM-DD');
          break;
        case 'yesterday':
          startDate = today.subtract(1, 'day').format('YYYY-MM-DD');
          endDate = startDate;
          break;
      }

      this.fetchData(startDate, endDate);
    }
  },
  mounted() {
    this.handleRangeChange();
  }
};
</script>
<style lang="less" scoped>
.statistics-container {
  padding: 20px;
  background-color: #f0f2f5;
}

.breadcrumb {
  margin-bottom: 20px;
}

.main-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.chart-container {
  background-color: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);

  h3 {
    color: #409EFF;
    margin-bottom: 15px;
    font-size: 18px;

    i {
      margin-right: 5px;
    }
  }
}

.chart {
  height: 400px;
  width:100%
}

.order-statistics {
  margin-bottom: 20px;
}

.stat-item {
  text-align: center;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;

  .stat-label {
    font-size: 14px;
    color: #606266;
    margin-bottom: 5px;
  }

  .stat-value {
     font-size:24px;
    font-weight: bold;
    color: #409EFF;
  }
}

.el-divider {
  margin: 30px 0;
}
</style>